#include "DXInput.h"

//////////////
// Keyboard //
//////////////

DXKeyboard::DXKeyboard (void)
{
}

DXKeyboard::DXKeyboard (HINSTANCE hInstance, HWND hWnd)
{
	Init(hInstance, hWnd);
}

DXKeyboard::~DXKeyboard (void)
{
	if (Keyboard)
		Keyboard->Unacquire();
	if (Interface)
		Interface->Release();
}

BOOL DXKeyboard::Init (HINSTANCE hInstance, HWND hWnd)
{
	BOOL Success = TRUE;

	DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&Interface, NULL);
	if (!Interface)
		Success = FALSE;
	else
	{
		Interface->CreateDevice(GUID_SysKeyboard, &Keyboard, NULL);
		if (!Keyboard)
			Success = FALSE;
		else
		{
			Keyboard->SetDataFormat(&c_dfDIKeyboard);
			Keyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
		}
	}

	return Success;
}

void DXKeyboard::Update (void)
{
	Keyboard->Acquire();
	Keyboard->GetDeviceState(256, (void*)KeyStates);
}

BOOL DXKeyboard::IsKeyDown (DWORD Key)
{
	BOOL Success = FALSE;
	if (KeyStates[Key] & 0x80)
		Success = TRUE;
	return Success;
}

///////////
// Mouse //
///////////

DXMouse::DXMouse (void)
{
}

DXMouse::DXMouse (HINSTANCE hInstance, HWND hWnd)
{
	Init(hInstance, hWnd);
}

DXMouse::~DXMouse (void)
{
	if (Mouse)
		Mouse->Unacquire();
	if (Interface)
		Interface->Release();
}

BOOL DXMouse::Init (HINSTANCE hInstance, HWND hWnd)
{
	BOOL Success = TRUE;

	DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&Interface, NULL);
	if (!Interface)
		Success = FALSE;
	else
	{
		Interface->CreateDevice(GUID_SysMouse, &Mouse, NULL);
		if (!Mouse)
			Success = FALSE;
		else
		{
			Mouse->SetDataFormat(&c_dfDIMouse);
			Mouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);
		}
	}

	return Success;
}

BOOL DXMouse::IsMouseClicked (DWORD Button)
{
	BOOL Success;
	if (MouseStates.rgbButtons[Button] & 0x80)
		Success = TRUE;
	return Success;
}

LONG DXMouse::GetMouseXChange (void)
{
	return MouseStates.lX;
}

LONG DXMouse::GetMouseYChange (void)
{
	return MouseStates.lY;
}

LONG DXMouse::GetMouseWheelChange (void)
{
	return MouseStates.lZ;
}